package com.jader.fragment;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jader.activities.SuoYouDetail;
import com.jader.adapter.MyAdapter_ALL;
import com.jader.beans.LunTan_All_Bens;
import com.jader.beans.User;
import com.jader.db.MyData;
import com.jader.myviews.CustomListView;
import com.jader.myviews.MyProgressDialog;
import com.jader.myviews.CustomListView.OnLoadMoreListener;
import com.jader.myviews.CustomListView.OnRefreshListener;
import com.jader.util.JaderApplication;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.zlp.jader.R;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.AdapterView.OnItemClickListener;

public class LunTan_AllFragment extends Fragment {

	View view;
	List<LunTan_All_Bens> list = new ArrayList<LunTan_All_Bens>();
	LayoutInflater mInflater;
	MyAdapter_ALL adapter_ALL;
	EditText pingluneEditText;
	Button fasongbButton;
	// ListView listView;
	CustomListView listView;
	SQLiteDatabase sqLiteDatabase;
	MyProgressDialog dialog;
	String url = JaderApplication.getIP() + "/Jader/SelectAll?type=30&page=";
	int page = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// list2=list.get(location)
	}
@Override
public void onResume() {
	// TODO Auto-generated method stub
	http(0);
	listView.invalidate();
	super.onResume();
}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = (View) inflater.inflate(R.layout.luntan_allfragment, null);
		initData();
		liebiao();
		getData();
		// showList(list);
		return view;
	}
	private void initData() {
		// TODO Auto-generated method stub
	}

	private void liebiao() {
		// 初始化尾部视图
		dialog = JaderApplication.getMyDialog(getActivity());
		mInflater = LayoutInflater.from(view.getContext());
		listView = (CustomListView) view.findViewById(R.id.luntan_all_listView);

		// 创建自定义适配器实例
		adapter_ALL = new MyAdapter_ALL(list, view.getContext());
		listView.setAdapter(adapter_ALL);
		listView.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				page = 0;
				http(0);
				// TODO 下拉刷新
				// loadData(0);
			}
		});

		listView.setOnLoadListener(new OnLoadMoreListener() {

			@Override
			public void onLoadMore() {
				// TODO 加载更多
				page = list.size();
				http(1);
				// loadData(1);

			}
		});
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(getActivity(), SuoYouDetail.class);
				intent.putExtra("position", list.get(position - 1));
				intent.putExtra("flag", position - 1);
				startActivity(intent);
			}
		});
	}

	// 监听列表单击事件
	//

	private void getData() {
		if (JaderApplication.isNetworkAvailable(LunTan_AllFragment.this.getActivity())) {
			http(1);
		}else {
			sqLiteDatabase = JaderApplication.getSqLiteDatabase();
			String sql="select * from "+MyData.tiezibiao;
			Cursor cursor=sqLiteDatabase.rawQuery(sql, null);
			list.clear();
			List<String> tupian=new ArrayList<String>();
			while (cursor.moveToNext()) {
				int i = 0;
				if (i >= 20) {
					break;
				}
				long tiezi_id=cursor.getLong(0);
				String date=cursor.getString(1);
				String tupian1=cursor.getString(2);
				String tupian2=cursor.getString(3);
				String tupian3=cursor.getString(4);
				String theme=cursor.getString(5);
				int praciteNumber=cursor.getInt(6);
				String hearphoto=cursor.getString(7);
				String username=cursor.getString(8);
				tupian.add(tupian1);
				tupian.add(tupian2);
				tupian.add(tupian3);
				list.add(new LunTan_All_Bens(tiezi_id, date, theme, null, praciteNumber, 0, 1, tupian, 1, new User(1, hearphoto, null, null, username, null, 0)));
				i++;
			}

			sqLiteDatabase.close();
		}
		
	}

	private void http(final int type) {
		HttpUtils httpUtils = new HttpUtils();
		if (JaderApplication.isNetworkAvailable(LunTan_AllFragment.this.getActivity())) {
			dialog.show();
		httpUtils.send(HttpMethod.GET, url + page,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub
						JaderApplication.show(getActivity(), "当前网络不可用，请检查网络连接或刷新");
						if (dialog.isShowing()) {
							dialog.dismiss();
						}
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						// TODO Auto-generated method stub
						Gson gson = new Gson();
						Type typelist = new TypeToken<List<LunTan_All_Bens>>() {
						}.getType();

						List<LunTan_All_Bens> liebiaos = gson.fromJson(
								arg0.result, typelist);
						if (type == 0) {
							// list.addAll(0,liebiaos);
							// 解决重复数据
							int result = 0;
							for (LunTan_All_Bens suoYou_Detail : liebiaos) {
								boolean flag = true;
								for (LunTan_All_Bens suoYou_Detail2 : list) {
									if (suoYou_Detail.equals(suoYou_Detail2)) {
										flag = false;
									}
								}
								if (flag) {
									list.add(result, suoYou_Detail);
									result++;
									adapter_ALL.notifyDataSetChanged();
								}
							}
							
							if (dialog.isShowing()) {
								dialog.dismiss();
							}
						} else if (type == 1) {
							for (LunTan_All_Bens suoYou_Detail : liebiaos) {

								boolean flag = true;
								for (LunTan_All_Bens suoYou_Detail2 : list) {
									if (suoYou_Detail.equals(suoYou_Detail2)) {
										flag = false;
									}
								}
								if (flag) {
									list.add(suoYou_Detail);
									adapter_ALL.notifyDataSetChanged();
								}
								
							}
							
							if (dialog.isShowing()) {
								dialog.dismiss();
							}
						}
						listView.onRefreshComplete();
						listView.onLoadMoreComplete();
					}
				});
	}else{
		JaderApplication.show(LunTan_AllFragment.this.getActivity(), "当前无网络，请检查网络情况");
		   if (dialog.isShowing()) {
			dialog.dismiss();
		}

	}
	}
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		sqLiteDatabase = JaderApplication.getSqLiteDatabase();
		if (MyData.tiezibiao != null) {
			String delete = "delete from " + MyData.tiezibiao;
			sqLiteDatabase.execSQL(delete);
		}
		sqLiteDatabase.close();
		
		for (int i = 0; i < 20; i++) {
			
			if (i < list.size()) {
				LunTan_All_Bens all_Bens = list.get(i);
				sqLiteDatabase = JaderApplication.getSqLiteDatabase();
				String insert = "insert into " + MyData.tiezibiao + " values(?,?,?,?,?,?,?,?,?)";
				
				if (all_Bens.getList().size() == 0) {

				}
				if (all_Bens.getList().size() == 1) {
					String[]  text = { all_Bens.getTieziId() + "", all_Bens.getDate(), all_Bens.getList().get(0),
						null, null, all_Bens.getTheme(),
						all_Bens.getPraiseNumber() + "", all_Bens.getUserBens().getPicture(),
						all_Bens.getUserBens().getUsername() };
					if (text != null) {
						sqLiteDatabase.execSQL(insert, text);
					}
				}
				if (all_Bens.getList().size() == 2) {
					String[] text = { all_Bens.getTieziId() + "", all_Bens.getDate(), all_Bens.getList().get(0),
							all_Bens.getList().get(1), null, all_Bens.getTheme(),
							all_Bens.getPraiseNumber() + "", all_Bens.getUserBens().getPicture(),
							all_Bens.getUserBens().getUsername() };
					if (text != null) {
						sqLiteDatabase.execSQL(insert, text);
						
					}
				}
				if (all_Bens.getList().size() > 2) {
					String[] text = { all_Bens.getTieziId() + "", all_Bens.getDate(), all_Bens.getList().get(0),
							all_Bens.getList().get(1),all_Bens.getList().get(2), all_Bens.getTheme(),
							all_Bens.getPraiseNumber() + "", all_Bens.getUserBens().getPicture(),
							all_Bens.getUserBens().getUsername() };
				
					if (text != null) {
						sqLiteDatabase.execSQL(insert, text);
					}
				}
				

				
				sqLiteDatabase.close();
			}
		}
	}
}